import { getStockPage, stockAdd } from "@/api/orderManag/godown";
import { DictTag } from "@/components/common/DictTag";
import { addDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep } from "@pureadmin/utils";
import dayjs from "dayjs";
import { h, onMounted, reactive, ref, toRaw } from "vue";
import editForm from "../form/index.vue";
import stockForm from "../form/stock.vue";
import type { FormItemProps } from "../utils/types";
//获取供应商名称
import { getSupplierSimplePage } from "@/api/basicArchives/supplierManagement";
//获取仓库名称
import { getDepositorySimplePage } from "@/api/basicArchives/warehouseManagement";
import { goodsCodeRend, goodsNameRend } from "@/utils/tableColumns";

export function useGodown() {
  const form = reactive({
    stockCode: undefined, // 入库单号
    purchaseOrderCode: undefined, // 备货订单号
    stockStatus: undefined, // 入库方式 1直接入库 2采购入库
    depositoryId: undefined, // 仓库id
    depositoryType: undefined, // 入库类型
    times: [],
    startTime: "", // 开始时间
    endTime: "" // 结束时间
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand"
    },
    {
      label: "业务日期",
      prop: "storeCode",
      formatter: ({ gmtModified }) => dayjs(gmtModified).format("YYYY-MM-DD"),
      minWidth: 130
    },
    {
      label: "入库单号",
      prop: "stockCode",
      minWidth: 130
    },
    {
      label: "入库仓库",
      prop: "depositoryType",
      minWidth: 130,
      cellRenderer: ({ row }) => <div>{row.depositoryName}</div>
    },
    {
      label: "入库方式",
      prop: "orderStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag
          dict-type="GODOWN_TYPE"
          type={
            row.stockStatus == 1
              ? "warning"
              : row.stockStatus == 2
                ? "success"
                : "info"
          }
          dict-value={row.stockStatus}
        />
      )
    },
    {
      label: "入库总数量",
      prop: "stockNum",
      minWidth: 120
    },
    {
      label: "备货订单号",
      prop: "purchaseOrderCode",
      minWidth: 135,
      showOverflowTooltip: true,
      formatter: ({ purchaseOrderCode }) => purchaseOrderCode || "--"
    },
    {
      label: "创建人",
      prop: "createUserName",
      width: 150
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      width: 180
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "specName",
      minWidth: 200,
      align: "left",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "specCode",
      align: "left",
      minWidth: 170,
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      prop: "barCode",
      minWidth: 120,
      formatter: ({ barCode }) => barCode || "--"
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "库存成本均价",
      prop: "avgBuyPrice",
      minWidth: 120,
      formatter: ({ avgBuyPrice }) => dealDataExcept(avgBuyPrice) || "--"
    },
    {
      label: "实际入库数量",
      prop: "stockNum",
      minWidth: 120
    },
    {
      label: "供应商名称",
      prop: "supplierName",
      minWidth: 120
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    if (form.times && form.times.length > 0) {
      form.startTime = form.times[0] + " 00:00:00";
      form.endTime = form.times[1] + " 23:59:59";
    } else {
      form.startTime = "";
      form.endTime = "";
    }

    const formData = cloneDeep(toRaw(form));
    delete formData.times;

    const params = {
      ...toRaw(formData),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const { data } = await getStockPage(params);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const formRef = ref();

  function openDialog(title = "直接入库", row?: FormItemProps) {
    addDialog({
      sureBtnLoading: true,
      title,
      props: {
        formInline: {
          id: row?.id ?? "",
          depositoryId: row?.depositoryId ?? undefined,
          depositoryType: 2,
          itemList: row?.itemList ?? [],
          stockStatus: 1
        },
        supplierList: supplierList.value,
        depositoryList: depositoryList.value
      },
      width: "1200px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done(); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);

            if (!curData.itemList || curData.itemList.length == 0) {
              closeLoading();
              return message("没有需要入库的商品", {
                type: "warning"
              });
            }

            const params = {
              // id: curData.id, // 主键id
              depositoryType: curData.depositoryType, // 仓库类型 1佳机仓库 2供应商仓库
              depositoryId: curData.depositoryId, // 仓库id
              stockStatus: curData.stockStatus, // 入库方式 1直接入库 2采购入库
              stockNum: 0,
              itemList: [] // 商品列表
            };
            let totalNum = 0;
            curData.itemList?.forEach(v => {
              if (v.goodsSpecList && v.goodsSpecList.length > 0) {
                v.goodsSpecList.forEach(vv => {
                  if (vv.rksl || v.rksl) {
                    params.itemList.push({
                      barCode: vv.barCode, // 商品条码
                      goodsCode: v.goodsCode, // 商品编码
                      goodsId: v.id, // 商品id
                      goodsName: v.goodsName, // 商品名称
                      goodsType: v.goodsType, // 商品类型 1抓机商品 2兑换礼品
                      specCode: vv.specCode, // 规格编码
                      specImageJson: vv.specImageJson || v.imageJson, // 规格编码
                      specName: vv.specName, // 规格名称
                      stockNum: vv.rksl || v.rksl // 入库数量
                    });
                    totalNum += Number(vv.rksl || v.rksl);
                  }
                });
              }
            });
            params.stockNum = totalNum;

            if (totalNum == 0) {
              closeLoading();
              return message("没有填写入库商品数量", {
                type: "warning"
              });
            }

            console.log("直接入库 === ", params);
            if (title === "直接入库") {
              await stockAdd(params)
                .then(() => chores())
                .catch(() => closeLoading());
            }
          } else {
            closeLoading();
          }
        });
      }
    });
  }

  function openStockDialog(title = "备货入库", row?: FormItemProps) {
    addDialog({
      sureBtnLoading: true,
      title,
      props: {
        formInline: {
          id: row?.id ?? "",
          purchaseOrderCode: row?.purchaseOrderCode ?? undefined,
          depositoryId: undefined,
          purchaseOrderId: row?.purchaseOrderId ?? undefined,
          itemList: row?.itemList ?? undefined,
          fareImageJson: row?.fareImageJson ?? undefined,
          sendImageJson: row?.sendImageJson ?? undefined,
          fare: row?.fare ?? undefined,
          fareType: 0,
          stockStatus: 2
        }
      },
      width: "1200px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(stockForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          console.log("curData", curData);
          if (curData.purchaseOrderCode) {
            if (!curData.sendImageJson) {
              message("请上传送货单", {
                type: "warning"
              });
            } else if (curData.fareType != 1 && !curData.fareImageJson) {
              message("请上传运费单", {
                type: "warning"
              });
            } else if (
              curData.fareType == 3 &&
              !curData.fare &&
              curData.fare !== 0
            ) {
              message("请输入运费", { type: "warning" });
            }
          }
          if (valid) {
            const params = {
              // id: curData.id, // 主键id
              depositoryType: 1, // 仓库类型 1佳机仓库 2供应商仓库
              depositoryId: curData.depositoryId, // 仓库id
              purchaseOrderCode: curData.purchaseOrderCode, // 备货订单号
              purchaseOrderId: curData.purchaseOrderId, // 备货订单id
              sendImageJson: curData.sendImageJson, // 送货单图片
              fareImageJson: curData.fareImageJson, // 运费到付图片
              fare: dealDataRide(curData.fare), // 运费到付金额
              stockStatus: curData.stockStatus, // 入库方式 1直接入库 2备货入库
              stockNum: 0,
              itemList: [] // 商品列表
            };

            let totalNum = 0;
            curData.itemList.forEach(v => {
              if (v.itemList && v.itemList.length > 0) {
                v.itemList.forEach(vv => {
                  if (vv.rksl || v.rksl) {
                    params.itemList.push({
                      purchaseOrderItemId: vv.id, // 采购订单详情id
                      barCode: vv.barCode, // 商品条码
                      goodsCode: vv.goodsCode, // 商品编码
                      goodsId: vv.goodsId, // 商品id
                      goodsName: vv.goodsName, // 商品名称
                      goodsType: vv.goodsType, // 商品类型 1抓机商品 2兑换礼品
                      specCode: vv.specCode, // 规格编码
                      specImageJson: vv.specImageJson || v.imageJson, // 规格编码
                      specName: vv.specName, // 规格名称
                      stockNum: vv.rksl || v.rksl // 入库数量
                    });
                    totalNum += Number(vv.rksl || v.rksl);
                  }
                });
              }
            });

            if (totalNum == 0) {
              closeLoading();
              return message("没有填写入库商品数量", {
                type: "warning"
              });
            }

            params.stockNum = totalNum;
            console.log("备货入库 =====", params);
            if (title === "备货入库") {
              await stockAdd(params)
                .then(() => chores())
                .catch(() => closeLoading());
            }
          } else {
            closeLoading();
          }
        });
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  let supplierList = ref([]);
  let depositoryList = ref([]);
  /**
   * 获取公共数据，包括供应商列表和仓库列表
   * 如果本地存储中没有这些数据，则从服务器获取并存储在本地
   * @param params - 查询参数
   */
  async function getCommon(params) {
    // 供应商列表
    getSupplierSimplePage(params).then(res => {
      supplierList.value = res.data?.records || [];
    });

    // 仓库列表
    getDepositorySimplePage({ typeList: [1, 2], ...params }).then(res => {
      depositoryList.value = res.data?.records || [];
    });
  }

  const activeName = ref("0");

  onMounted(() => {
    onSearch();

    // 供应商列表
    const params = {
      status: 0,
      pageNum: 1,
      pageSize: 9999
    };
    getCommon(params);
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    pagination,
    activeName,
    supplierList,
    depositoryList,
    useRenderIcon,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    openDialog,
    openStockDialog
  };
}
